import store from '../../store';
export default {
    doCall: function (functionName, data, callback,otherParams) {
        let _this = this;
        // 解决连续调用问题
        if (this.lastCallTime && (Date.now() - this.lastCallTime) < 100) {
            setTimeout(function () {
                _this.doCall(functionName, data, callback);
            }, 100);
            return;
        }
        this.lastCallTime = Date.now();

        data = data || {};

        //回调方法
        if (callback) {
            let callbackName = _this.callback(callback);
            if(!otherParams){
                otherParams = {callback: callbackName};
            }else{
                otherParams.callback = callbackName;
            }
            data = Object.assign({},data, otherParams);
        }
        if (!store.state.deviceType) {
            window.webkit.messageHandlers[functionName].postMessage(JSON.stringify(data));
        } else if (store.state.deviceType) {
			if(JSON.stringify(data)=='{}'){
				window.secTrade && window.secTrade[functionName] && window.secTrade[functionName]();
			}else{
				window.secTrade && window.secTrade[functionName] && window.secTrade[functionName](JSON.stringify(data));
			}
        } else {
            console.error('未获取platform信息，调取api失败');
        }
    },
    random: function () {
        let random = new Date().getTime() + '_' + parseInt(Math.random() * 1000000);

        return random;
    },
    callback: function (fn) {
        let that = this;
        let random = that.random();
        
        let callbackName = 'jsBridge_Callbacks_' + random;

        window[callbackName] = (function (cb, callbackName) {
            return function (res) {
                if(typeof cb != 'string'){
                    cb.apply(this, arguments);
                }else{
                    window[cb].apply(this, arguments);
                }
                
                delete window[callbackName];
            };
        })(fn, callbackName);

        return callbackName;
    }
}